package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.task.Content;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private IDeviceDataService deviceDataService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate0;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(Device device)
    {
        int result = deviceMapper.updateById(device);

        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        BatchUpdateDeviceNicknameResponse response;
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> nicknameInfos = new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setDeviceName(device.getDeviceName());
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setProductKey(device.getProductKey());
        nicknameInfo.setIotId(device.getIotId());
        nicknameInfos.add(nicknameInfo);
        request.setDeviceNicknameInfo(nicknameInfos);
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("更新iot出错啦");
        }
        if (!response.getBody().getSuccess()){
            throw new BaseException("更新iot出错啦");
        }
        return result;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void sysProductList() throws Exception {

        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(10);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductListResponse response = client.queryProductList(request);
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.body.data.list.productInfo;
        redisTemplate.opsForValue().set(CacheConstants.SYNCPRODUCTLIST_ALL, JSON.toJSONString(productInfo));

    }

    @Override
    public List<ProductVo> allProduct() {
        String s = redisTemplate.opsForValue().get(CacheConstants.SYNCPRODUCTLIST_ALL);
        List<ProductVo> list = JSONUtil.toList(s, ProductVo.class);
        return list;
    }

    @Override
    public void register(DeviceDto deviceDto) {
        //查询数据库中设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.lambdaQuery(Device.class).eq(Device::getDeviceName, deviceDto.getDeviceName()));

        //如果重复直接结束
        if(count>0){
            throw new BaseException("设备名称以重复,请从新选择");
        }
        //不重复调用iot接口注册设备
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException("设备注册失败");
        }
        //判断位置是否为0，如果是0为随身设备，物理位置类型为-1
        if(deviceDto.getLocationType()==0){
            deviceDto.setPhysicalLocationType(-1);
        }
        //补全iotid到设备对象中
        deviceDto.setIotId(response.getBody().getData().getIotId());
        //保存设备到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        try {
            int result = deviceMapper.insert(device);
            if(result <= 0){
                deleteIotDevice(deviceDto);
                throw new BaseException("老人/位置已经被绑定");
            }
        } catch (Exception e) {
            deleteIotDevice(deviceDto);
            throw new BaseException("老人/位置已经被绑定");
        }

    }

    private void deleteIotDevice(DeviceDto deviceDto) {
        //如果保存失败，删除iot平台上新增的设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceName(deviceDto.getDeviceName());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("iot平台设备删除失败");
        }
    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {

        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!response.body.success){
            throw new BaseException("查询设备详情失败");
        }
        DeviceVo deviceVo = BeanUtil.toBean(response.body.data, DeviceVo.class);

        Device device = deviceMapper.selectOne(Wrappers.lambdaQuery(Device.class).eq(Device::getIotId, deviceDto.getIotId()));
        BeanUtil.copyProperties(device,deviceVo);
        return deviceVo;
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("查询物模型失败");
        }
        return AjaxResult.success(response.body.data);
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("查询设备属性失败");
        }
        return AjaxResult.success(response.body.data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(Device device) {

        LambdaQueryWrapper<Device> w = Wrappers.lambdaQuery(Device.class).eq(Device::getIotId, device.getIotId());
        deviceMapper.delete(w);
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(device.getIotId());
        request.setProductKey(device.getProductKey());
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除设备失败");
        }
        if(!response.body.success){
            throw new BaseException("删除设备失败");
        }

    }

    @Override
    public void batchSave(Content content) {
        Device device = deviceMapper.selectOne(Wrappers.lambdaQuery(Device.class).eq(Device::getIotId, content.getIotId()));
        if(ObjectUtil.isEmpty(device)){
            return;
        }
        List<DeviceData> list = new ArrayList<>();
        content.getItems().forEach((key,val)->{
            DeviceData build = DeviceData.builder()
                    .deviceName(device.getDeviceName())
                    .iotId(content.getIotId())
                    .nickname(device.getNickname())
                    .productKey(device.getProductKey())
                    .productName(device.getProductName())
                    .functionId(key)
                    .accessLocation(device.getRemark())
                    .locationType(device.getLocationType())
                    .physicalLocationType(device.getPhysicalLocationType())
                    .deviceDescription(device.getDeviceDescription())
                    .dataValue(val.getValue()+"")
                    .alarmTime(LocalDateTimeUtil.of(val.getTime()))
                    .build();
            list.add(build);
        });
        deviceDataService.saveBatch(list);
        redisTemplate0.opsForHash().put(CacheConstants.IOT_DEVICE_DATA_LASTED, content.getIotId(),list );
        List<DeviceData> list1 = (List<DeviceData>) redisTemplate0.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LASTED, content.getIotId());
        System.out.println(list1);
    }
}
